package com.example.news.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.news.R;
import com.example.news.bean.NewsBean;
import com.example.news.databinding.NewsItemBinding;
import com.example.news.helper.OnItemClickListener;

import java.net.URL;
import java.util.List;

public class NewsDataBindingAdapter extends RecyclerView.Adapter<NewsDataBindingAdapter.ViewHolder> {
   Context context;
   private OnItemClickListener listener;


   private List<NewsBean> lists;

   public NewsDataBindingAdapter(Context context,List<NewsBean> lists) {
      this.context=context;this.lists = lists;

   }
   public void change(List<NewsBean> lists)
   {
      this.lists=lists;
      notifyDataSetChanged();
   }

   @Override
   public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
      ViewHolder viewHolder = new ViewHolder(view);
//      view.setOnClickListener(v -> {
//         if(listener != null){
//            listener.onItemClick(v,viewType);
//         }
//      });
      return new ViewHolder(view);
   }

   @Override
   public void onBindViewHolder(ViewHolder holder, int position) {
      holder.title.setText(lists.get(position).getTitle());
      holder.category.setText(lists.get(position).getCategory());
      holder.newsId = lists.get(position).getNewsId();
      int a=position;
      holder.title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if (listener != null) {
                  listener.onItemClick(v,a);
               }
            }
         });
      holder.category.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (listener != null) {
               listener.onItemClick(v,a);
            }
         }
      });
   }

   @Override
   public int getItemCount() {
      return lists.size();
   }

   public static class ViewHolder extends RecyclerView.ViewHolder {
      public TextView title;
      public TextView category;
      private String newsId;
      public ViewHolder(View itemView) {
         super(itemView);
         title=itemView.findViewById(R.id.news_title);
         category=itemView.findViewById(R.id.category);
      }
   }
   public void setOnItemClickListener(OnItemClickListener listener) {
      this.listener = listener;
   }
}

